package com.ruicar.afs.cloud.basic.proceeds.pay.controller;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruicar.afs.cloud.basic.common.service.BasicMainInfoService;
import com.ruicar.afs.cloud.basic.proceeds.pay.condition.PayListQueryCondition;
import com.ruicar.afs.cloud.basic.proceeds.pay.entity.BasicAutoPaymentConfig;
import com.ruicar.afs.cloud.basic.proceeds.pay.entity.BasicPaymentBank;
import com.ruicar.afs.cloud.basic.proceeds.pay.entity.BasicPaymentPool;
import com.ruicar.afs.cloud.basic.proceeds.pay.service.BasicAutoPaymentConfigService;
import com.ruicar.afs.cloud.basic.proceeds.pay.service.BasicPaymentPoolService;
import com.ruicar.afs.cloud.common.core.exception.AfsBaseException;
import com.ruicar.afs.cloud.common.core.util.IResponse;
import com.ruicar.afs.cloud.common.modules.contract.enums.PaymentStatusEnum;
import com.ruicar.afs.cloud.common.modules.contract.enums.YesOrNoEnum;
import com.ruicar.afs.cloud.common.util.EmptyUtils;
import com.ruicar.afs.cloud.components.datadicsync.DicHelper;
import com.ruicar.afs.cloud.components.datadicsync.dto.DicDataDto;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@RestController
@Api("付款管理")
@RequestMapping("/pay")
@AllArgsConstructor
public class PayManagermentController {

	private final BasicPaymentPoolService paymentPoolService;
	private final BasicMainInfoService basicMainInfoService;
	private final BasicAutoPaymentConfigService basicAutoPaymentConfigService;

	@PostMapping(value = "/queryPayRecordList")
	@ApiOperation(value = "查询付款信息")
	public IResponse queryDebitPayBatch(@ModelAttribute PayListQueryCondition payListQueryCondition) {
		payListQueryCondition.setPaymentStatusList(Arrays.asList(payListQueryCondition.getPaymentStatus().split(",")));
		IResponse response = paymentPoolService.queryPayMentByQueryParam(payListQueryCondition);

		return response;
	}
	@PostMapping(value = "/exportPayList")
	@ApiOperation(value = "付款信息导出")
	public IResponse exportPayList(@ModelAttribute PayListQueryCondition payListQueryCondition) {
		payListQueryCondition.setPaymentStatusList(Arrays.asList(payListQueryCondition.getPaymentStatus().split(",")));
		IResponse response = paymentPoolService.exportPayList(payListQueryCondition);

		return response;
	}

	@PostMapping(value = "/sendPayOrderForIds")
	public IResponse sendPayOrderForIds(@RequestParam("ids") String ids) {
		List<Long> idList = Arrays.stream(ids.split(",")).map(s -> Long.parseLong(s.trim())).collect(Collectors.toList());
		String contractNos = "";

		/**  付款通道 by ZC.GUO  **/
		Map<String, List<DicDataDto>> map = DicHelper.getDicMaps("mappingBank");
		List<DicDataDto> list = map.get("mappingBank");
		Map<String,String> mappingBankMap = new HashMap<>(list.size());
		if (EmptyUtils.isNotEmpty(list)){
			list.forEach(dto->{
				mappingBankMap.put(dto.getValue(),dto.getTitle());
			});
		}else{
			return IResponse.fail("未配置睿易通通道数据字典，字典类型值为：mappingBank");
		}


		for (Long id : idList) {

			BasicPaymentPool pool = paymentPoolService.getOne(Wrappers.<BasicPaymentPool>query().lambda()
					.eq(BasicPaymentPool::getId, id)
					.ne(BasicPaymentPool::getIsPaying, YesOrNoEnum.yes)
					.in(BasicPaymentPool::getPaymentStatus,PaymentStatusEnum.waitPayment,PaymentStatusEnum.failPayment)
			);
			if (EmptyUtils.isEmpty(pool)){
				/**  已付款或正在付款，跳过该条数据 by ZC.GUO  **/
				continue;
			}
			/**  锁定 by ZC.GUO  **/
			pool.setIsPaying(YesOrNoEnum.yes);
			if (paymentPoolService.readySingleWhenStartPay(pool)){
				try{
					/**  匹配付款账号 by ZC.GUO  **/
					BasicPaymentBank payAccount = basicAutoPaymentConfigService.takePayAccount(pool.getReceiptBankCode());
					if (EmptyUtils.isNotEmpty(payAccount)) {
						/**  付款通道 by ZC.GUO  **/
						String chlCd = mappingBankMap.get(payAccount.getPaymentBankCode());
						if (EmptyUtils.isNotEmpty(chlCd)) {
							paymentPoolService.sendPaymentPool(pool,chlCd,payAccount);
						}else {
							contractNos += pool.getContractNo() + ",";
						}
					} else {
						contractNos += pool.getContractNo() + ",";
					}
				}catch (Exception e){
					throw new AfsBaseException(e.getMessage());
				}finally{
					/**  解锁 by ZC.GUO  **/
					pool.setIsPaying(YesOrNoEnum.no);
					paymentPoolService.readySingleWhenStartPay(pool);
				}
			}
		}
		if (contractNos.equals("")) {
			return IResponse.success("付款发送成功");
		} else {
			return IResponse.fail("合同号：" + contractNos + "不存在有效的付款账号或付款账号通道未配置，发送失败");
		}
	}
	
	
	/**
	 * 手动查询付款结果
	 * @author ZC.GUO
	 * @param 
	 * @return 
	 */
	@PostMapping(value = "/queryPayResultForIds")
	public IResponse queryPayResultForIds(@RequestParam("ids") String ids) {
		List<Long> idList = Arrays.stream(ids.split(",")).map(s -> Long.parseLong(s.trim())).collect(Collectors.toList());
		List<BasicPaymentPool> listPool = paymentPoolService.list(Wrappers.<BasicPaymentPool>query().lambda()
				.in(BasicPaymentPool::getId,idList)
				.eq(BasicPaymentPool::getPaymentStatus, PaymentStatusEnum.paying)
		);
		List<String> msgidList = new ArrayList<>();
		if (EmptyUtils.isNotEmpty(listPool)){
			for (BasicPaymentPool pool:listPool){
				if (!msgidList.contains(pool.getMsgid())){
					paymentPoolService.queryPayResult(pool.getMsgid());
					msgidList.add(pool.getMsgid());
				}
			}
		}
		return IResponse.success("查询成功");
	}
	/**
	 * 暂停付款
	 * @author ZC.GUO
	 * @param
	 * @return
	 */
	@PostMapping(value = "/stopPayForIds")
	@Transactional(rollbackFor = Exception.class)
	public IResponse stopPayForIds(@RequestParam("ids") String ids) {
		List<Long> idList = Arrays.stream(ids.split(",")).map(s -> Long.parseLong(s.trim())).collect(Collectors.toList());
		if (EmptyUtils.isNotEmpty(idList)){
			List<BasicAutoPaymentConfig> autoPaymentConfigList = basicAutoPaymentConfigService.list();
			if (EmptyUtils.isNotEmpty(autoPaymentConfigList)){
				BasicAutoPaymentConfig autoPaymentConfig = autoPaymentConfigList.get(0);
				/**  只允许自动付款关闭进行暂停付款操作 by ZC.GUO  **/
				if (YesOrNoEnum.no.equals(autoPaymentConfig.getEnableAutoPay())){
					for (Long id :idList){
						BasicPaymentPool pool = paymentPoolService.getById(id);
						if (EmptyUtils.isNotEmpty(pool)){
							if (!YesOrNoEnum.yes.equals(pool.getIsPayment())){
								return IResponse.fail("操作失败，合同号"+pool.getContractNo()+"已是暂停付款状态，请重新操作");
							}
						}

					}
					paymentPoolService.update(Wrappers.<BasicPaymentPool>update().lambda()
							.in(BasicPaymentPool::getId,idList)
							.set(BasicPaymentPool::getIsPayment,YesOrNoEnum.no)
					);
				}else {
					return IResponse.fail("只允许自动付款关闭进行暂停付款操作");
				}
			}else{
				return IResponse.fail("只允许自动付款关闭进行暂停付款操作");
			}
		}
		return IResponse.success("操作成功");
	}
	/**
	 * 取消暂停付款
	 * @author ZC.GUO
	 * @param
	 * @return
	 */
	@PostMapping(value = "/cancelStopPayForIds")
	@Transactional(rollbackFor = Exception.class)
	public IResponse cancelStopPayForIds(@RequestParam("ids") String ids) {
		List<Long> idList = Arrays.stream(ids.split(",")).map(s -> Long.parseLong(s.trim())).collect(Collectors.toList());
		if (EmptyUtils.isNotEmpty(idList)){
			for (Long id :idList){
				BasicPaymentPool pool = paymentPoolService.getById(id);
				if (EmptyUtils.isNotEmpty(pool)){
					if (!YesOrNoEnum.no.equals(pool.getIsPayment())){
            			return IResponse.fail("操作失败，合同号"+pool.getContractNo()+"已非暂停付款状态，请重新操作");
					}
				}

			}
			paymentPoolService.update(Wrappers.<BasicPaymentPool>update().lambda()
					.in(BasicPaymentPool::getId,idList)
					.set(BasicPaymentPool::getIsPayment,YesOrNoEnum.yes)
			);
		}
		return IResponse.success("操作成功");
	}
	/**
	 * 付款异常处理
	 * @author ZC.GUO
	 * @param
	 * @return
	 */
	@PostMapping(value = "/handleExceptionForIds")
	public IResponse handleExceptionForIds(@RequestParam("ids") String ids) {
		List<Long> idList = Arrays.stream(ids.split(",")).map(s -> Long.parseLong(s.trim())).collect(Collectors.toList());

		paymentPoolService.handleExceptionForPayment(idList);

		return IResponse.success("操作成功");
	}
	/**
	 * 发送修改收款账号短信
	 * @author ZC.GUO
	 * @param
	 * @return
	 */
	@PostMapping(value = "/sendMsgToAdmin")
	public IResponse sendMsgToAdmin(@RequestParam("ids") String ids) {
		List<Long> idList = Arrays.stream(ids.split(",")).map(s -> Long.parseLong(s.trim())).collect(Collectors.toList());
		List<BasicPaymentPool> poolList = paymentPoolService.listByIds(idList);
		if(EmptyUtils.isNotEmpty(poolList)){
			for (BasicPaymentPool pool : poolList) {
				paymentPoolService.sendMsgAndUpdatePool(pool);
			}
		}
		return IResponse.success("操作成功");
	}
	/**
	 * 更新收款账号信息
	 * @author ZC.GUO
	 * @param
	 * @return
	 */
	@PostMapping(value = "/updateReceiptAccount")
	public IResponse updateReceiptAccount(@RequestParam("ids") String ids) {
		List<Long> idList = Arrays.stream(ids.split(",")).map(s -> Long.parseLong(s.trim())).collect(Collectors.toList());
		List<BasicPaymentPool> poolList = paymentPoolService.listByIds(idList);
		if(EmptyUtils.isNotEmpty(poolList)){
			for (BasicPaymentPool pool : poolList) {
				paymentPoolService.queryAndChangeAccountInfo(pool);
			}
		}
		return IResponse.success("操作成功");
	}

}
